package com.example.wkable.exoplayer

import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.widget.Toast
import com.example.wkable.exoplayer.extensions.checkPermission
import com.example.wkable.exoplayer.extensions.toast
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.source.DefaultMediaSourceEventListener
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.MediaSourceEventListener
import com.google.android.exoplayer2.source.dash.DashMediaSource
import com.google.android.exoplayer2.source.hls.HlsMediaSource
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource
import com.google.android.exoplayer2.ui.PlayerView
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Log
import com.google.android.exoplayer2.util.Util
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException


class MainActivity : AppCompatActivity() {
    private val playerView by lazy {
        findViewById<PlayerView>(R.id.exo_player)
    }
    private val exoPlayer by lazy {
        ExoPlayerFactory.newSimpleInstance(applicationContext)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (!checkPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, 34)) {
            return
        }

        initView()

    }

    private fun initView() {

        exo_player.player = exoPlayer

        playerView.player = exoPlayer

        // file:///android_asset/...
        // android.resource://package_name/raw/sample.png
        val defaultDataSourceFactory = DefaultDataSourceFactory(
            applicationContext,
            Util.getUserAgent(applicationContext, packageName)
        )
        val uri = Uri.parse("http://184.72.239.149/vod/smil:BigBuckBunny.smil/playlist.m3u8")
        val mediaSource = buildMediaSource(uri, null, defaultDataSourceFactory)

        exoPlayer.repeatMode = Player.REPEAT_MODE_ONE
        mediaSource.addEventListener(Handler(), object : DefaultMediaSourceEventListener() {
            override fun onLoadError(
                windowIndex: Int,
                mediaPeriodId: MediaSource.MediaPeriodId?,
                loadEventInfo: MediaSourceEventListener.LoadEventInfo?,
                mediaLoadData: MediaSourceEventListener.MediaLoadData?,
                error: IOException?,
                wasCanceled: Boolean
            ) {
                Log.e(TAG, "onLoadError:$error")
                runOnUiThread {
                    toast(this@MainActivity, "loadError:$error", Toast.LENGTH_LONG)
                }
            }

        })

        exoPlayer.prepare(mediaSource)
        exoPlayer.addListener(object : Player.EventListener {
            override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
                Log.e(TAG, "onPlayerStateChanged:$playWhenReady state:$playbackState")
                if (playbackState == Player.STATE_READY) {
                }
            }

            override fun onPlayerError(error: ExoPlaybackException?) {
                Log.e(TAG, "onPlayerError:$error")
            }


            override fun onTimelineChanged(timeline: Timeline?, manifest: Any?, reason: Int) {
                val period = Timeline.Period()
                Log.e(
                    TAG, "periodCount:${timeline?.periodCount}->windowCount:${timeline?.windowCount}" +
                            "->timeLine.durationMs:${timeline?.getPeriod(0, period)?.durationMs}"
                )
            }

            override fun onSeekProcessed() {

            }

            override fun onPositionDiscontinuity(reason: Int) {

            }
        })
        exoPlayer.playWhenReady = true


    }



    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == 34) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                toast(this, "获取权限失败!", Toast.LENGTH_LONG)
                return
            }
            initView()
        }
    }

    companion object {
        private const val VIDEO_PATH = "DCIM/Camera/VID_20190131_153530.mp4"
        //        private const val VIDEO_PATH = "DCIM/Camera/VID_20190131_1535301.mp4"
        private const val TAG = "MainActivity"

        private fun buildMediaSource(uri: Uri, overrideExtension: String?, factory: DataSource.Factory): MediaSource {
            val type = Util.inferContentType(
                if (!TextUtils.isEmpty(overrideExtension))
                    ".$overrideExtension"
                else
                    uri.lastPathSegment
            )
            Log.e(TAG, "uri.lastPathSegment:${uri.lastPathSegment}")
            return when (type) {
                C.TYPE_SS -> {
                    SsMediaSource.Factory(factory).createMediaSource(uri)
                }
                C.TYPE_DASH -> {
                    DashMediaSource.Factory(factory).createMediaSource(uri)
                }
                C.TYPE_HLS -> {
                    HlsMediaSource.Factory(factory).createMediaSource(uri)
                }
                C.TYPE_OTHER -> {
                    ExtractorMediaSource.Factory(factory).createMediaSource(uri)
                }
                else -> {
                    throw IllegalStateException("Unsupported type: $type")
                }
            }
        }

    }

    override fun onResume() {
        super.onResume()
        Log.e(TAG, "onResume:${exoPlayer.playbackState}")
        if (exoPlayer.playbackState == Player.STATE_READY) {
            exoPlayer.playWhenReady = true
        }
    }

    override fun onPause() {
        super.onPause()
        if (exoPlayer.playbackState == Player.STATE_READY) {
            exoPlayer.playWhenReady = false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        exoPlayer.stop()
        exoPlayer.release()
    }


}
